﻿using dz.u9.jky.schema.ARBill;
using System.Collections.Generic;
using UFIDA.U9.ISV.AR;
using UFIDA.U9.CBO.Pub.Controller;
using System;
using UFIDA.U9.CBO.SCM.Customer;
using dz.u9.jky.schema.Common;

namespace dz.inner.jky.api.service
{
    internal class ARBillService : BaseService
    {
        public U9CResult Add(DzARBillHeadDTO dto)
        {
            return util.U9Invoke(__Add, dto);
        }

        private U9CResult __Add(DzARBillHeadDTO dto)
        {
            try
            {
                CreateImportARBillSV sv = new CreateImportARBillSV();

                sv.ImportARBillHeadDTOs = Convert(dto);

                var rtn = sv.Do();

                U9CResult result = new U9CResult();

                if (rtn != null && rtn.Count > 0)
                {
                    result.Id = rtn[0].ID;
                    result.DocNo = rtn[0].DocNO;
                    result.IsSuccess = true;
                }
                else
                {
                    result.IsSuccess = false;
                    result.Message = "创建应收单失败";
                }

                return result;
            }
            catch (Exception ex)
            {
                return new U9CResult
                {
                    IsSuccess = false,
                    Message = $"创建应收单发生异常: {ex.Message}"
                };
            }
        }

        private List<ImportARBillHeadDTO> Convert(DzARBillHeadDTO arBill)
        {
            if (arBill == null)
                return null;

            ImportARBillHeadDTO headDTO = new ImportARBillHeadDTO();

            // 设置基本属性
            headDTO.DocNo = arBill.DocNo;
            headDTO.IsPeriodBegin = false;

            // 添加这些客户信息映射
            headDTO.AccrueCust = new CustomerMISCInfo { Code = arBill.AccrueCust };
            headDTO.PayCust = new CustomerMISCInfo { Code = arBill.PayCust };

            // 处理行项目
            if (arBill.ARBillLines != null && arBill.ARBillLines.Count > 0)
            {
                List<ImportARBillLineDTO> lineDTOs = new List<ImportARBillLineDTO>();

                int lineNo = 1;
                foreach (var line in arBill.ARBillLines)
                {
                    ImportARBillLineDTO lineDTO = new ImportARBillLineDTO();

                    // 结算数量
                    lineDTO.PUAmount = line.PUAmount;
                    // 结算单价
                    lineDTO.UnitPrice = line.UnitPrice;

                    // 计算税额（假设税率为13%）
                    decimal taxRate = 0.13m;
                    decimal goodTaxOC = line.IsIncludeTax ?
                        line.PUAmount * line.UnitPrice * taxRate / (1 + taxRate) :
                        line.PUAmount * line.UnitPrice * taxRate;

                    lineDTOs.Add(lineDTO);
                }

                headDTO.ImportARBillLineDTOs = lineDTOs;
            }

            return new List<ImportARBillHeadDTO>() { headDTO };
        }
    }
}